package com.easy.sys.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easy.common.bean.SysRole;
import com.easy.common.enumbean.RoleStatus;
import com.easy.common.service.IRoleService;
import com.easy.sys.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleService implements IRoleService {
    @Autowired
    SysRoleMapper sysRoleMapper;

    @Override
    public SysRole insert(SysRole role) {
        sysRoleMapper.insert(role);
        SysRole result=this.getByID(role.getId());
        return result;
    }

    @Override
    public SysRole update(SysRole role) {
        sysRoleMapper.updateById(role);
        SysRole result=this.getByID(role.getId());
        return result;
    }

    @Override
    public int delete(Integer id) {
        int result=sysRoleMapper.deleteById(id);
        return result;
    }

    @Override
    public SysRole getByID(Integer id) {
        SysRole result=sysRoleMapper.selectById(id);
        return result;
    }

    @Override
    public IPage<SysRole> getListByPage(IPage page, SysRole role) {
        Wrapper wrapper = new QueryWrapper(role);
        IPage<SysRole> result=sysRoleMapper.selectPage(page, wrapper);
        return result;
    }

    @Override
    public List<SysRole> getList(SysRole role) {
        Wrapper wrapper = new QueryWrapper(role);
        List<SysRole> result=sysRoleMapper.selectList(wrapper);
        return result;
    }

    @Override
    public int setStatus(Integer id) {
        SysRole role = this.getByID(id);
        if (role != null) {
            // 切换角色状态
            if (role.getStatus() == RoleStatus.DISABLE) {
                role.setStatus(RoleStatus.NORMAL);
                sysRoleMapper.updateById(role);  // 保存更改到数据库
                return 1;
            } else {
                role.setStatus(RoleStatus.DISABLE);
                sysRoleMapper.updateById(role);  // 保存更改到数据库
                return 0;
            }
        }
        return -1; // 角色不存在，返回-1表示操作失败
    }

    @Override
    public SysRole assignPermission(SysRole role) {
        // 获取现有角色信息
        SysRole existingRole = this.getByID(role.getId());
        if (existingRole != null) {
            // 更新角色的权限信息
            // 注意：这里假设权限信息已经包含在传入的role对象中
            // 如果有专门的权限字段，需要单独设置
            sysRoleMapper.updateById(role);
            return this.getByID(role.getId());
        }
        return null;
    }
}
